package com.qujia.web.controller.system;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.qujia.station.domain.NoInsensAccInfoVO;
import com.qujia.station.domain.Station;
import com.qujia.system.domain.SysRoleMenu;
import com.qujia.system.mapper.SysMenuMapper;
import com.qujia.system.mapper.SysRoleMapper;
import com.qujia.system.mapper.SysRoleMenuMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qujia.common.annotation.Log;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysRole;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.enums.BusinessType;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.ServletUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.common.utils.poi.ExcelUtil;
import com.qujia.framework.web.service.SysPermissionService;
import com.qujia.framework.web.service.TokenService;
import com.qujia.system.service.ISysRoleService;
import com.qujia.system.service.ISysUserService;

import javax.annotation.Resource;

/**
 * 角色信息
 * 
 * @author qujia
 */
@RestController
@RequestMapping("/system/role")
@Api(tags = "角色管理")
public class SysRoleController extends BaseController
{
    @Autowired
    private ISysRoleService roleService;

    @Resource
    private ISysUserService sysUserService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysMenuMapper menuMapper;

    @Resource
    private SysRoleMenuMapper roleMenuMapper;




    @Autowired
    private SysPermissionService permissionService;
    
    @Autowired
    private ISysUserService userService;

    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    @ApiOperation(value = "角色列表", httpMethod = "GET")
    public TableDataInfo list(SysRole role)
    {
        LoginUser current = SecurityUtils.getLoginUser();
        if (SecurityUtils.isAdmin(current.getUser().getUserId())) {
            startPage();
            List<SysRole> list = roleService.selectAllRoleList(role);
            return getDataTable(list);
        }else{
            Long userId  = current.getUser().getUserId();
            role.setCreateUserId(userId);
            startPage();
            List<SysRole> list = roleService.selectRoleList(role);
            return getDataTable(list);
        }

    }

    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/listForAdmin")
    @ApiOperation(value = "角色列表", httpMethod = "GET")
    public TableDataInfo listForAdmin(SysRole role)
    {
        LoginUser current = SecurityUtils.getLoginUser();
        if (SecurityUtils.isAdmin(current.getUser().getUserId())) {
            startPage();
            role.setCreateUserId(1L);
            List<SysRole> list = roleService.selectAllRoleList(role);
            return getDataTable(list);
        }else{
            Long userId  = current.getUser().getUserId();
            role.setCreateUserId(userId);
            startPage();
            List<SysRole> list = roleService.selectRoleList(role);
            return getDataTable(list);
        }

    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @GetMapping("/export")
    @ApiOperation(value = "角色导出", httpMethod = "GET")
    public AjaxResult export(SysRole role)
    {
        LoginUser current = SecurityUtils.getLoginUser();
        if (SecurityUtils.isAdmin(current.getUser().getUserId())) {
            startPage();
            List<SysRole> list = roleService.selectAllRoleList(role);
            ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
            return util.exportExcel(list, "角色数据");
        }else{
            Long userId  = current.getUser().getUserId();
            role.setCreateUserId(userId);
            startPage();
            List<SysRole> list = roleService.selectRoleList(role);
            ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
            return util.exportExcel(list, "角色数据");
        }
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId)
    {
        return AjaxResult.success(roleService.selectRoleById(roleId));
    }
    public static String generateTimestamp() {
        // 生成当前的时分秒时间戳
        LocalTime currentTime = LocalTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
        String timeString = currentTime.format(formatter);

        // 生成三位随机数
        Random random = new Random();
        int randomNum = random.nextInt(1000); // 生成0到999之间的随机数
        String randomString = String.format("%03d", randomNum); // 格式化为三位数字字符串

        // 拼接时分秒时间戳和三位随机数
        String timestamp = timeString + randomString;

        return timestamp;
    }
    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "角色新增", httpMethod = "POST")
    public AjaxResult add(@RequestBody SysRole role)
    {
//        生成的时分秒时间戳+三位随机数的数字字符串
        String timestamp = generateTimestamp();
        role.setRoleKey(timestamp);
        LoginUser current = SecurityUtils.getLoginUser();
        Long userId  = current.getUser().getUserId();
        role.setCreateUserId(userId);
        if (SecurityUtils.isAdmin(current.getUser().getUserId())) {
            role.setCreateLevel(0);
        }else{
            role.setCreateLevel(Integer.parseInt(current.getUser().getUserLevel()));
        }
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 一键开启
     */
    @Log(title = "角色菜单一键开启roleId 和 menuIds", businessType = BusinessType.UPDATE)
    @PostMapping("/roleMenuOpen")
    @ApiOperation(value = "角色菜单一键开启", httpMethod = "POST")
    public AjaxResult roleMenuOpen(@Validated @RequestBody SysRole role)
    {
        Long  roleId =  role.getRoleId();

        List<Long> roleIds = roleMapper.selectAllRoleIdByRoleId(roleId);
        roleIds.add(roleId);
        Long[] menuIds = role.getMenuIds();
        for(Long roleIdItem : roleIds){
            SysRole roleOneDetail = roleMapper.selectRoleById(roleIdItem);
            List<Integer> listMenu = menuMapper.selectSysRoleMenuByRoleId(roleIdItem);

            // 使用 Set 来去重
            Set<Long> menuSet = new HashSet<>();
            for (Integer menuId : listMenu) {
                menuSet.add(menuId.longValue());
            }

            // 将 menuIds 中的数据添加到 Set 中
            for (Long menuId : menuIds) {
                menuSet.add(menuId);
            }

            // 将 Set 转换为 Long[]
            Long[] mergedMenuList = menuSet.toArray(new Long[0]);

            roleOneDetail.setRoleId(roleIdItem);

            roleOneDetail.setMenuIds(mergedMenuList);

            this.edit(roleOneDetail);
        }
        AjaxResult ajax = AjaxResult.success();
        return ajax;
    }

    /**
     * 一键开启
     */
    @Log(title = "角色菜单一键关闭roleId 和 menuIds", businessType = BusinessType.UPDATE)
    @PostMapping("/roleMenuClose")
    @ApiOperation(value = "角色菜单一键关闭", httpMethod = "POST")
    public AjaxResult roleMenuClose(@Validated @RequestBody SysRole role)
    {
        Long  roleId =  role.getRoleId();

        List<Long> roleIds = roleMapper.selectAllRoleIdByRoleId(roleId);
        roleIds.add(roleId);
        Long[] menuIds = role.getMenuIds();
        for(Long roleIdItem : roleIds){
            SysRole roleOneDetail = roleMapper.selectRoleById(roleIdItem);
            List<Integer> listMenu = menuMapper.selectSysRoleMenuByRoleId(roleIdItem);
            // 使用 Set 来去重
            Set<Long> menuSet = new HashSet<>();
            for (Integer menuId : listMenu) {
                menuSet.add(menuId.longValue());
            }

            // 从 menuSet 中删除 menuIds 中的数据，仅删除存在的元素
            for (Long menuId : menuIds) {
                if (menuSet.contains(menuId)) {
                    menuSet.remove(menuId);
                }
            }

            // 将 Set 转换为 Long[]
            Long[] mergedMenuList = menuSet.toArray(new Long[0]);


            roleOneDetail.setRoleId(roleIdItem);

            roleOneDetail.setMenuIds(mergedMenuList);

            this.edit(roleOneDetail);
        }
        AjaxResult ajax = AjaxResult.success();
        return ajax;
    }


    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "角色修改", httpMethod = "PUT")
    public AjaxResult edit(@Validated @RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        
        if (roleService.updateRole(role) > 0)
        {
            // 更新缓存用户权限
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
            {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return AjaxResult.success();
        }
        return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable Long[] roleIds)
    {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {

        return AjaxResult.success(roleService.selectRoleAll());
    }
}
